import cssStyle from './index.module.css'
import ReactDOM from 'react-dom'
import React from 'react'
import PropTypes from 'prop-types'

let toaskStyle = {
    'success': {
        color: '#4fca13',
        background: '#f0f9eb',
        borderColor: '#c2e7b0',
    },
    'info': {
        color: '#909399',
        background: '#f4f4f5',
        borderColor: '#d3d4d6'
    },
    'warning': {
        color: '#E6A23C',
        background: '#fdf6ec',
        borderColor: '#faecd8'
    },
    'error': {
        color: '#f56c6c',
        background: '#fef0f0',
        borderColor: '#fbc4c4'
    }
}

class ToaskComponent extends React.PureComponent{
    toaskRef = React.createRef()
    componentDidMount(){
        window.requestAnimationFrame(() => {
            setTimeout(() => {
                if (this.toaskRef.current) {
                    this.toaskRef.current.style.top = '10%'
                    this.toaskRef.current.style.opacity = 1
                    if(this.props.duration === 0){
                        window.addEventListener('hashchange', this.close)
                    }
                }
            })
        })
    }
    componentWillUnmount(){
        window.removeEventListener('hashchange', this.close)
    }
    close = (() => {
        this.toaskRef.current.style.top = 0
        this.toaskRef.current.style.opacity = 0
        this.props.close()
    }).bind(this)
    render(){
        let style = toaskStyle[this.props.type]
        return(
            <div ref={ this.toaskRef } className={ cssStyle.toask } style={ style }>
                <p>{ this.props.title }</p>
                { parseFloat(this.props.duration) > 0 ? null : <span className={ cssStyle.close } onClick={ this.close }>x</span> }
            </div>
        )
    }
}

ToaskComponent.propTypes = {
    show: PropTypes.bool,
    type: PropTypes.string,
    title: PropTypes.string,
    duration: PropTypes.number,
    close: PropTypes.func
}

function Toask(){
    let toaskContainer = null
    let toaskRef = React.createRef()
    let timer = null
    function hideToask(){
        if(toaskContainer){
            if(timer){
                return
            }
            timer = setTimeout(() => {
                ReactDOM.unmountComponentAtNode(toaskContainer)
                document.body.removeChild(toaskContainer)
                toaskContainer = null
            }, 300)
        }
    }
    return{
        showToask(props){
            toaskContainer = document.createElement('div')
            document.body.appendChild(toaskContainer)
            ReactDOM.render(
                <ToaskComponent ref={ toaskRef } {...props} close={ hideToask } />,
                toaskContainer
            )
            if(parseFloat(props.duration) > 0){
                setTimeout(() => {
                    if(toaskRef.current){
                        toaskRef.current.close()
                    }
                }, props.duration)
            }
        }
    }
}

export default Toask